-- curl -i '127.0.0.1:6699/api/tt/thread_spawn'

-- 同时查询 mysql、 memcached 和一个远程 HTTP 服务
-- 以它们实际返回结果的顺序进行输出

 local mysql = require "resty.mysql"
 local memcached = require "resty.memcached"
 local F    = require "base_funs"
 local cjson = require "cjson"

ngx.say("thread_spawn!")

 local function query_mysql()
     local db = mysql:new()


    local ok, err, errno, sqlstate = db:connect{
                    host = "127.0.0.1",
                    port = 3306,
                    database = "test",
                    user = "root",
                    password = "123456",
                    max_packet_size = 1024 * 1024 }
    if not ok then
        ngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate)
        return
    end

    res, err, errno, sqlstate =
                     db:query("select * from item order by id asc", 10)
    if not res then
        ngx.say("bad result: ", err, ": ", errno, ": ", sqlstate, ".")
        return
    end

    
     db:set_keepalive(0, 100)

    
     -- ngx.say("mysql done: ", cjson.encode(res))
     F._eachi(res, ngx.say)

     for index,value in ipairs(res) do
    ngx.say(index .."\t",value)
  end


     ngx.say("mysql done! " .. type(err))
 end

 local function query_memcached()
     local memc = memcached:new()
     memc:connect("127.0.0.1", 11211)
     local res, err = memc:get("some_key")
     ngx.say("memcached done: ", res)
 end

 local function query_http()
     local res = ngx.location.capture("/my-http-proxy")
     ngx.say("http done: ", res.body)
 end

 ngx.thread.spawn(query_mysql)      -- 创建线程 1
 ngx.thread.spawn(query_memcached)  -- 创建线程 2
 ngx.thread.spawn(query_http)       -- 创建线程 3